import os
from celery import Celery, platforms
from django.conf import settings
# https://docs.celeryq.dev/en/latest/userguide/configuration.html


# 设置系统环境变量,安装django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings')
REDIS_CONN = f'redis://:{settings.REDIS_PWD}@{settings.REDIS_HOST}:{settings.REDIS_PORT}'
print("REDIS_CONN:",REDIS_CONN)
# 消息broker
broker_url = f"{REDIS_CONN}/8"
# 存储任务状态及结果 django存储/redis
# result_backend = "django-db"
result_backend = f"{REDIS_CONN}/9"





## 项目名，注册Celery的APP
app = Celery('devops', 
broker=broker_url, # 代理人
backend=result_backend,  # 存储结果
result_expires= 60 * 1,
CELERYD_CONCURRENCY = 5,    # celery worker并发数
CELERYD_MAX_TASKS_PER_CHILD = 10,  # 每个worker最大执行任务数,避免内存泄漏

# Django Admin添加周期性任务将任务调度器设为DatabaseScheduler;
beat_scheduler="django_celery_beat.schedulers:DatabaseScheduler"
)

CELERYD_FORCE_EXECV = True  # 非常重要,有些情况下可以防止死锁

# 指定从django的settings.py里读取celery配置；namespace='CELERY'作用是允许所有Celery配置项必须以CELERY开头，防止冲突
app.config_from_object('django.conf:settings', namespace='CELERY')
## 自动发现各个app下的tasks.py文件
app.autodiscover_tasks()

## 允许root 用户运行celery
platforms.C_FORCE_ROOT = True

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))


# 时区
app.conf.timezone = 'Asia/Shanghai'
# 是否使用UTC
app.conf.enable_utc = False



from datetime import timedelta
from celery.schedules import crontab
app.conf.beat_schedule = {
     "add-every-30s": {
         "task": "app.tasks.add",
         'schedule': 30.0, # 每30秒执行1次
         'args': (3, 8) # 传递参数-
     },
     "add-every-day": {
         "task": "app.tasks.add",
         'schedule': timedelta(hours=1), # 每小时执行1次
         'args': (3, 8) # 传递参数-
     },
    'add-task': {
        'task': 'celery_task.task1.add',
        'schedule': crontab(hour=8, day_of_week=1),  # 每周一早八点
        'args': (30, 20),
    }
}